package cn.wolfcode.wolf2w.listener;


import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.KeyManager;
import cn.wolfcode.wolf2w.vo.StrategyStatisVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * redis缓存数据初始化监听器
 *
 * mongodb -----> redis
 * 1>攻略统计对象 vo
 * 2>用户攻略收藏列表
 */
//@Component    //交给spring容器管理
public class RedisInitListener implements ApplicationListener<ContextRefreshedEvent> {  //选择第一个监听事件

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private StringRedisTemplate template;

    //spring 容器启动并初始化之后马上执行该方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        System.out.println("初始化-----------");
        //从数据库里面获取vo对象
        List<Strategy> list = strategyService.list();

        //遍历list
        for (Strategy strategy : list) {
            //新建对象
            StrategyStatisVO vo = new StrategyStatisVO();
            //从源赋值给vo
            BeanUtils.copyProperties(strategy, vo);
            //设值给vo
            vo.setStrategyId(strategy.getId());
            //获取key
            String key = KeyManager.STRATEGY_STATIS_VO.join(strategy.getId());
            //存在则不新增, 将vo对象存到redis
            template.opsForValue().setIfAbsent(key, JSON.toJSONString(vo));
        }


        System.out.println("销毁----");

    }
}
